package com.zhxxfwzx.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhxxfwzx.common.lang.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description TODO
 * @title: JwtAuthenticationEntryPoint
 * @Author LiJing
 * @Date: 2021/6/178:47 上午
 * @Version 1.0
 */
@Slf4j
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.info("认证失败，未登录");
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter out = response.getWriter();
        RespBean result = RespBean.error("请先登录!");
        out.write(new ObjectMapper().writeValueAsString(result));
        out.flush();
        out.close();

    }
}
